﻿//-----------------------------------------------------------------------
// <copyright file="GroupModule.cs" company="Nathan Miller">
// Copyright (c) Nathan Miller.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
//-----------------------------------------------------------------------
namespace App.Modules.Group
{
    using App.Modules.Message;
    using App.Modules.Scene;
    using TileTool.Action.Message;
    using TileTool.Editor.Command;
    using TileTool.Log;
    using TileTool.Message;
    using TileTool.Scene;
    using TileTool.Scene.Action.Group;
    using TileTool.Scene.Entity;
    using TileTool.Scene.Entity.Group;

    /// <summary>
    /// Module which handles group related actions.
    /// </summary>
    public class GroupModule : Module
    {
        #region Constants - Private

        /// <summary>
        /// Log message group.
        /// </summary>
        private const string LogGroup = "GroupModule";

        #endregion

        #region Methods - Public

        /// <summary>
        /// Called when the application is starting up.
        /// </summary>
        public override void Startup()
        {
            LogSystem.LogStartup(LogGroup, "Starting...");

            base.Startup();
        }

        /// <summary>
        /// Register for messages.
        /// </summary>
        public override void RegisterForMessages()
        {
            base.RegisterForMessages();

            MessageModule messageModule = this.GetModule<MessageModule>();
            MessageRouter router = messageModule.MessageRouter;

            router.RegisterForMessage<CommandIdMessage>(
                this.HandleCreateGroupCommandIDMessage,
                MessageHandlerPriority.Default,
                new CommandIdMessageFilter(EditorCommandIds.CreateGroupCommand));

            router.RegisterForMessage<CommandIdMessage>(
                this.HandleDestroyGroupCommandIDMessage,
                MessageHandlerPriority.Default,
                new CommandIdMessageFilter(EditorCommandIds.DestroyGroupCommand));

            router.RegisterForMessage<CommandIdMessage>(
                this.HandleOpenCloseGroupCommandIDMessage,
                MessageHandlerPriority.Default,
                new CommandIdMessageFilter(EditorCommandIds.ToggleGroupOpenCloseCommand));
        }

        /// <summary>
        /// Unregister for messages.
        /// </summary>
        public override void UnregisterForMessages()
        {
            base.UnregisterForMessages();

            MessageModule messageModule = this.GetModule<MessageModule>();
            MessageRouter router = messageModule.MessageRouter;

            router.UnregisterForMessage<CommandIdMessage>(this.HandleCreateGroupCommandIDMessage);
            router.UnregisterForMessage<CommandIdMessage>(this.HandleDestroyGroupCommandIDMessage);
            router.UnregisterForMessage<CommandIdMessage>(this.HandleOpenCloseGroupCommandIDMessage);
        }

        #endregion

        #region Methods - Private

        /// <summary>
        /// Handles creating a group from the currently selected objects.
        /// </summary>
        private void HandleCreateGroup()
        {
            SceneModule sceneModule = this.GetModule<SceneModule>();
            ISceneManager manager = sceneModule.Scene;
            IEntityCollection selection = manager.Selection;

            if (selection.Count == 0)
            {
                LogSystem.LogInfo(LogGroup, "Attempting to create group from empty selection. Ignoring.");
                return;
            }

            CreateGroupAction action = new CreateGroupAction(manager, selection);

            action.Do();

            this.SendMessage(new ActionMessage(action));
        }

        /// <summary>
        /// Handles destroying a group from the currently selected objects.
        /// </summary>
        private void HandleDestroyGroup()
        {
            SceneModule sceneModule = this.GetModule<SceneModule>();
            ISceneManager manager = sceneModule.Scene;
            IEntityCollection selection = manager.Selection;

            if (selection.Count == 0)
            {
                LogSystem.LogInfo(LogGroup, "Attempting to destroy a group from empty selection. Ignoring.");
                return;
            }

            DestroyGroupAction action = new DestroyGroupAction(manager, selection);

            action.Do();

            this.SendMessage(new ActionMessage(action));
        }

        /// <summary>
        /// Handle opening and closing groups in the selection.
        /// </summary>
        private void HandleOpenCloseGroup()
        {
            SceneModule sceneModule = this.GetModule<SceneModule>();
            ISceneManager manager = sceneModule.Scene;
            IEntityCollection selection = manager.Selection;

            if (selection.Count == 0)
            {
                LogSystem.LogInfo(LogGroup, "Attempting to open / close a group from empty selection. Ignoring.");
                return;
            }

            OpenCloseGroupAction action = new OpenCloseGroupAction(manager, selection);

            action.Do();

            this.SendMessage(new ActionMessage(action));
        }

        #endregion

        #region Methods - Private - Message handlers

        /// <summary>
        /// Handle a create group command ID message.
        /// </summary>
        /// <param name="message">Command ID message to handle.</param>
        /// <returns>Returns if the message was handled or not.</returns>
        private MessageHandlerResult HandleCreateGroupCommandIDMessage(CommandIdMessage message)
        {
            this.HandleCreateGroup();
            return MessageHandlerResult.Ignored;
        }

        /// <summary>
        /// Handle a destroy group command ID message.
        /// </summary>
        /// <param name="message">Command ID message to handle.</param>
        /// <returns>Returns if the message was handled or not.</returns>
        private MessageHandlerResult HandleDestroyGroupCommandIDMessage(CommandIdMessage message)
        {
            this.HandleDestroyGroup();
            return MessageHandlerResult.Ignored;
        }

        /// <summary>
        /// Handle a group open / close command ID message.
        /// </summary>
        /// <param name="message">Command ID message to handle.</param>
        /// <returns>Returns if the message was handled or not.</returns>
        private MessageHandlerResult HandleOpenCloseGroupCommandIDMessage(CommandIdMessage message)
        {
            this.HandleOpenCloseGroup();
            return MessageHandlerResult.Ignored;
        }

        #endregion
    }
}
